package org.ands.data;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.io.FileInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.lang.Exception;

import org.ands.apps.PropertyHelper;
import org.supercsv.io.CsvBeanReader;
import org.supercsv.io.ICsvBeanReader;
import org.supercsv.prefs.CsvPreference;
import org.supercsv.cellprocessor.ift.CellProcessor;
import org.supercsv.cellprocessor.constraint.Unique;
import org.supercsv.cellprocessor.constraint.StrMinMax;



// TODO: Auto-generated Javadoc
/**
 * Constructs lists of XMLContents objects for different scenarios.
 * 
 * @see 		Contents
 * @author      Melanie Adamson
 * @version     1.0                   
 * @since       2012-07-20
 */
public class ContentsRetrieverCSV implements IClientContentsRetriever {
	
	/**
	 * Defines CellProcessor for input csv file.
	 * 
	 * @see 		org.supercsv.cellprocessor.ift.CellProcessor
	 * @author      Melanie Adamson
	 * @version     1.0                   
	 * @since       2012-07-20
	 */
	static final CellProcessor[] XMLContentProcessors = new CellProcessor[] {
        new Unique(new StrMinMax(0, 1000)),
        null
    };
	
		
	
	/* (non-Javadoc)
	 * @see org.ands.data.IContentsRetriever#getXmlContents(org.ands.apps.PropertyHelper)
	 */
	@Override
	public Map<Integer, List<Contents>> getXmlContentsFromClient(final PropertyHelper propertyHelper) 
					throws Exception{
		
		final String csvFileName = propertyHelper.getProperty("CSV_INPUT", true);
				
		InputStream inputStream = new FileInputStream(csvFileName);
		InputStreamReader reader = new InputStreamReader(inputStream);
		
		ICsvBeanReader beanReader = new CsvBeanReader(reader, CsvPreference.STANDARD_PREFERENCE);
		ArrayList<Contents> list = new ArrayList<Contents>();
		
		final String[] columnNames = beanReader.getCSVHeader(true);
		Contents xmlContents;
		while ( (xmlContents = beanReader.read(Contents.class, columnNames, XMLContentProcessors)) != null) {
			list.add(xmlContents);
		}
	
		if (list.size() <= 0){
			throw new Exception("No list of XMLContents created.");
		}
			
		
		Map<Integer, List<Contents>> xmlContentsMap = new HashMap<Integer, List<Contents>>();
		xmlContentsMap.put(1, list);
		
		return xmlContentsMap;
		
	}

	/* (non-Javadoc)
	 * @see org.ands.data.IContentsRetriever#getOutFileFromConfig(org.ands.apps.PropertyHelper)
	 */
	@Override
	public String getOutFileFromConfig(final PropertyHelper propertyHelper)
			throws Exception {
		
		return propertyHelper.getProperty("RIF_CS_XML_OUT_FROM_CSV", true);
	}
	
	/**
	 * Gets the spatial xml rif-cs from a kml file contents.
	 *
	 * @return the xml contents
	 * @throws Exception the exception
	 */
	public Map<Integer, List<Contents>> getSpatialFromKML(final String kmlFileName, final int fileCount) throws Exception{
		assert(false);
		throw new Exception("Not implemented");
	}
		
}



